#include <sys/types.h>
#include <sys/socket.h>
#include <unistd.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <iostream>
using namespace std;
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cerr << "usage:" << argv[0] << "error" << endl;
        exit(0);
    }
    string serverip = argv[1];
    uint16_t serverport = htons(stoi(argv[2]));
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = inet_addr(serverip.c_str());
    server.sin_port = serverport;
    int sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
    if (sockfd < 0)
    {
        cout << "create socket error"<< endl;
        exit(1);
    }
    // 客户端一定要知道服务器的ip和端口
    // 客户端的端口号一般不由用户自己设定，而是OS随机选择，服务器一定要自己设定
    // 客户端首次向服务器发送数据的时候，OS会自动给client绑定
    while (1)
    {
        string msg;
        cout << "enter：";
        std::getline(std::cin, msg);
        int n = sendto(sockfd, msg.c_str(), msg.size(), 0, (struct sockaddr *)&server, sizeof(server));
        if (n > 0)
        {
            char buf[512];
            struct sockaddr_in serverin;
            socklen_t len;
            int m = recvfrom(sockfd, buf, sizeof(buf) - 1, 0, (struct sockaddr *)&serverin, &len);
            if (m > 0)
            {
                buf[m] = 0;
                cout << buf << endl;
            }
            else
            {
                break;
            }
        }
        else
        {
            break;
        }
    }
    ::close(sockfd);
}